package com.example.black.myapplication.shader;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.example.black.myapplication.R;

/**
 * <pre>
 *     author : 28476
 *     e-mail : hao.wang@1hai.cn
 *     time   : 2019/01/01/17:01
 *     desc   :
 *     version: 1.0
 * </pre>
 */

public class MyLinearGradientView extends View {

    private Bitmap bitmap;
    private BitmapShader bitmapShader;
    private int[] colors = {Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW};
    private Paint paint;
    private int width;
    private int height;
    private int min;
    private LinearGradient linearGradient;

    public MyLinearGradientView(Context context) {
        super(context);
        initConfig();
    }

    public MyLinearGradientView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initConfig();
    }

    public MyLinearGradientView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initConfig();
    }

    private void initConfig() {
        bitmap = ((BitmapDrawable) (getResources().getDrawable(R.drawable.avatar3))).getBitmap();
        width = bitmap.getWidth();
        height = bitmap.getHeight();
        min = Math.min(bitmap.getWidth(), bitmap.getHeight());
        /*
         * CLAMP 平铺 REPEAT 重复 MIRROR 镜像
         */
        bitmapShader = new BitmapShader(bitmap,Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);
        linearGradient = new LinearGradient(0, 0, 400, 400, colors, null, Shader.TileMode.REPEAT);
        // bitmapShader = new BitmapShader(bitmap,Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);
       // bitmapShader = new BitmapShader(bitmap,Shader.TileMode.MIRROR,Shader.TileMode.MIRROR);
        paint = new Paint();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(getResources().getColor(R.color.white));
       // canvas.drawBitmap(bitmap,0,0,paint);
        paint.setShader(linearGradient);
        canvas.drawRect(0, 0, 400, 400, paint);
    }
}
